<html><head><meta charset="utf-8"><title>29 押宝线程源码面试题-慕课专栏</title>
			<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
			<meta name="renderer" content="webkit">
			<meta property="qc:admins" content="77103107776157736375">
			<meta property="wb:webmaster" content="c4f857219bfae3cb">
			<meta http-equiv="Access-Control-Allow-Origin" content="*">
			<meta http-equiv="Cache-Control" content="no-transform ">
			<meta http-equiv="Cache-Control" content="no-siteapp">
			<link rel="apple-touch-icon" sizes="76x76" href="https://www.imooc.com/static/img/common/touch-icon-ipad.png">
			<link rel="apple-touch-icon" sizes="120x120" href="https://www.imooc.com/static/img/common/touch-icon-iphone-retina.png">
			<link rel="apple-touch-icon" sizes="152x152" href="https://www.imooc.com/static/img/common/touch-icon-ipad-retina.png">
			<link href="https://moco.imooc.com/captcha/style/captcha.min.css" rel="stylesheet">
			<link rel="stylesheet" href="https://www.imooc.com/static/moco/v1.0/dist/css/moco.min.css?t=201907021539" type="text/css">
			<link rel="stylesheet" href="https://www.imooc.com/static/lib/swiper/swiper-3.4.2.min.css?t=201907021539">
			<link rel="stylesheet" href="https://static.mukewang.com/static/css/??base.css,common/common-less.css?t=2.5,column/zhuanlanChapter-less.css?t=2.5,course/inc/course_tipoff-less.css?t=2.5?v=201907051055" type="text/css">
			<link charset="utf-8" rel="stylesheet" href="https://www.imooc.com/static/lib/ueditor/themes/imooc/css/ueditor.css?v=201907021539"><link rel="stylesheet" href="https://www.imooc.com/static/lib/baiduShare/api/css/share_style0_16.css?v=6aba13f0.css"></head>
			<body><div id="main">


<div class="main-con hide-menu">
    <!-- 左侧菜单 & 索引 -->
    
    <div class="right-content" style="padding-left: 0px;">
        <div class="container clearfix" id="top" style="width: 1134px; display: block;">
            
            
            <div class="center_con js-center_con l" style="width: 1134px;">
                <div class="article-con">
                                            <!-- 买过的阅读 -->
                        

                    
                    <div class="art-title" style="margin-top: 0px;">
                        29 押宝线程源码面试题
                    </div>
                    <div class="art-info clearfix">
                        
                        <span class="l">
                            更新时间：2019-11-06 09:54:20
                        </span>
                    </div>
                    <div class="art-top">
                                                <img src="https://img.mukewang.com/5dba924e0001139406400359.jpg" alt="">
                                                                        <div class="famous-word-box">
                            <img src="https://www.imooc.com/static/img/column/bg-l.png" alt="" class="bg1 bg">
                            <img src="https://www.imooc.com/static/img/column/bg-r.png" alt="" class="bg2 bg">
                            <div class="famous-word">如果不想在世界上虚度一生，那就要学习一辈子。<p class="author">——高尔基</p></div>
                        </div>
                                            </div>
                    <div class="art-content js-lookimg">
                        <div id="article_content">
                            <div class="cl-preview-section"><h2 id="引导语" style="font-size: 30px;">引导语</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">关于线程方面的面试题，大部分都是概念题，我们需要大概的清楚这些概念，和面试官达成共识即可，本章我们一起来看下这些面试题，对前两章的学习进行巩固。</p>
</div><div class="cl-preview-section"><h2 id="面试题" style="font-size: 30px;">1 面试题</h2>
</div><div class="cl-preview-section"><h3 id="创建子线程时，子线程是得不到父线程的-threadlocal，有什么办法可以解决这个问题？">1.1 创建子线程时，子线程是得不到父线程的 ThreadLocal，有什么办法可以解决这个问题？</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：这道题主要考察线程的属性和创建过程，可以这么回答。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">可以使用 InheritableThreadLocal 来代替 ThreadLocal，ThreadLocal 和 InheritableThreadLocal 都是线程的属性，所以可以做到线程之间的数据隔离，在多线程环境下我们经常使用，但在有子线程被创建的情况下，父线程 ThreadLocal 是无法传递给子线程的，但 InheritableThreadLocal 可以，主要是因为在线程创建的过程中，会把</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">InheritableThreadLocal 里面的所有值传递给子线程，具体代码如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token comment">// 当父线程的 inheritableThreadLocals 的值不为空时</span>
<span class="token comment">// 会把 inheritableThreadLocals 里面的值全部传递给子线程</span>
<span class="token keyword">if</span> <span class="token punctuation">(</span>parent<span class="token punctuation">.</span>inheritableThreadLocals <span class="token operator">!=</span> null<span class="token punctuation">)</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>inheritableThreadLocals <span class="token operator">=</span>
        ThreadLocal<span class="token punctuation">.</span><span class="token function">createInheritedMap</span><span class="token punctuation">(</span>parent<span class="token punctuation">.</span>inheritableThreadLocals<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><h3 id="线程创建有几种实现方式？">1.2 线程创建有几种实现方式？</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：主要有三种，分成两大类，第一类是子线程没有返回值，第二类是子线程有返回值。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">无返回值的线程有两种写法，第一种是继承 Thread，可以这么写：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">class</span> <span class="token class-name">MyThread</span> <span class="token keyword">extends</span> <span class="token class-name">Thread</span><span class="token punctuation">{</span>
  <span class="token annotation punctuation">@Override</span>
  <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span>Thread<span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">extendThreadInit</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">new</span> <span class="token class-name">MyThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">第二种是实现 Runnable 接口，并作为 Thread 构造器的入参，代码如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java">Thread thread <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token annotation punctuation">@Override</span>
  <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"{} begin run"</span><span class="token punctuation">,</span>Thread<span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 开一个子线程去执行</span>
thread<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这两种都会开一个子线程去执行任务，并且是没有返回值的，如果需要子线程有返回值，需要使用 Callable 接口，但 Callable 接口是无法直接作为 Thread 构造器的入参的，必须结合 FutureTask 一起使用，可以这样写代码：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testThreadByCallable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> ExecutionException<span class="token punctuation">,</span> InterruptedException <span class="token punctuation">{</span>
  FutureTask futureTask <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">FutureTask</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Callable</span><span class="token operator">&lt;</span>String<span class="token operator">&gt;</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> String <span class="token function">call</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
      Thread<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">3000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      String result <span class="token operator">=</span> <span class="token string">"我是子线程"</span><span class="token operator">+</span>Thread<span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"子线程正在运行：{}"</span><span class="token punctuation">,</span>Thread<span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">return</span> result<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span>futureTask<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"返回的结果是 {}"</span><span class="token punctuation">,</span>futureTask<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">把 FutureTask 作为 Thread 的入参就可以了，FutureTask 组合了 Callable ，使我们可以使用 Callable，并且 FutureTask 实现了 Runnable 接口，使其可以作为 Thread 构造器的入参，还有 FutureTask 实现了 Future，使其对任务有一定的管理功能。</p>
</div><div class="cl-preview-section"><h3 id="子线程-1-去等待子线程-2-执行完成之后才能执行，如何去实现？">1.3 子线程 1 去等待子线程 2 执行完成之后才能执行，如何去实现？</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：这里考察的就是 Thread.join 方法，我们可以这么做：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testJoin2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
  Thread thread2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"我是子线程 2,开始沉睡"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">try</span> <span class="token punctuation">{</span>
        Thread<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span>2000L<span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"我是子线程 2，执行完成"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  Thread thread1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"我是子线程 1，开始运行"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token keyword">try</span> <span class="token punctuation">{</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"我是子线程 1，我在等待子线程 2"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token comment">// 这里是代码关键  </span>
      thread2<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"我是子线程 1，子线程 2 执行完成，我继续执行"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"我是子线程 1，执行完成"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  thread1<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  thread2<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  Thread<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">100000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">子线程 1 需要等待子线程 2，只需要子线程 1 运行的时候，调用子线程 2 的 join 方法即可，这样线程 1 执行到 join 代码时，就会等待线程 2 执行完成之后，才会继续执行。</p>
</div><div class="cl-preview-section"><h3 id="守护线程和非守护线程的区别？如果我想在项目启动的时候收集代码信息，请问是守护线程好，还是非守护线程好，为什么？">1.4 守护线程和非守护线程的区别？如果我想在项目启动的时候收集代码信息，请问是守护线程好，还是非守护线程好，为什么？</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：两者的主要区别是，在 JVM 退出时，JVM 是不会管守护线程的，只会管非守护线程，如果非守护线程还有在运行的，JVM 就不会退出，如果没有非守护线程了，但还有守护线程的，JVM 直接退出。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">如果需要在项目启动的时候收集代码信息，就需要看收集工作是否重要了，如果不太重要，又很耗时，就应该选择守护线程，这样不会妨碍 JVM 的退出，如果收集工作非常重要的话，那么就需要非守护进程，这样即使启动时发生未知异常，JVM 也会等到代码收集信息线程结束后才会退出，不会影响收集工作。</p>
</div><div class="cl-preview-section"><h3 id="线程-start-和-run-之间的区别。">1.5 线程 start 和 run 之间的区别。</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：调用 Thread.start 方法会开一个新的线程，run 方法不会。</p>
</div><div class="cl-preview-section"><h3 id="thread、runnable、callable-三者之间的区别。">1.6 Thread、Runnable、Callable 三者之间的区别。</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：Thread 实现了 Runnable，本身就是 Runnable，但同时负责线程创建、线程状态变更等操作。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Runnable 是无返回值任务接口，Callable  是有返回值任务接口，如果任务需要跑起来，必须需要 Thread 的支持才行，Runnable 和 Callable 只是任务的定义，具体执行还需要靠 Thread。</p>
</div><div class="cl-preview-section"><h3 id="线程池-submit-有两个方法，方法一可接受-runnable，方法二可接受-callable，但两个方法底层的逻辑却是同一套，这是如何适配的。">1.7 线程池 submit 有两个方法，方法一可接受 Runnable，方法二可接受 Callable，但两个方法底层的逻辑却是同一套，这是如何适配的。</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：问题考察点在于 Runnable 和 Callable 之间是如何转化的，可以这么回答。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Runnable 和 Callable 是通过 FutureTask 进行统一的，FutureTask 有个属性是 Callable，同时也实现了 Runnable 接口，两者的统一转化是在 FutureTask 的构造器里实现的，FutureTask 的最终目标是把 Runnable 和 Callable 都转化成 Callable，Runnable 转化成 Callable 是通过 RunnableAdapter 适配器进行实现的。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">线程池的 submit 底层的逻辑只认 FutureTask，不认 Runnable 和 Callable 的差异，所以只要都转化成 FutureTask，底层实现都会是同一套。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">具体 Runnable 转化成 Callable 的代码和逻辑可以参考上一章，有非常详细的描述。</p>
</div><div class="cl-preview-section"><h3 id="callable-能否丢给-thread-去执行？">1.8 Callable 能否丢给 Thread 去执行？</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：可以的，可以新建 Callable，并作为 FutureTask 的构造器入参，然后把 FutureTask 丢给 Thread 去执行即可。</p>
</div><div class="cl-preview-section"><h3 id="futuretask-有什么作用谈谈对-futuretask-的理解。">1.9 FutureTask 有什么作用(谈谈对 FutureTask 的理解)。</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：作用如下：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">组合了 Callable，实现了 Runnable，把 Callable 和 Runnnable 串联了起来。</li>
<li style="font-size: 20px; line-height: 38px;">统一了有参任务和无参任务两种定义方式，方便了使用。</li>
<li style="font-size: 20px; line-height: 38px;">实现了 Future 的所有方法，对任务有一定的管理功能，比如说拿到任务执行结果，取消任务，打断任务等等。</li>
</ol>
</div><div class="cl-preview-section"><h3 id="聊聊对-futuretask-的-get、cancel-方法的理解">1.10 聊聊对 FutureTask 的 get、cancel 方法的理解</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：get 方法主要作用是得到 Callable 异步任务执行的结果，无参 get 会一直等待任务执行完成之后才返回，有参 get 方法可以设定固定的时间，在设定的时间内，如果任务还没有执行成功，直接返回异常，在实际工作中，建议多多使用 get 有参方法，少用 get 无参方法，防止任务执行过慢时，多数线程都在等待，造成线程耗尽的问题。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">cancel 方法主要用来取消任务，如果任务还没有执行，是可以取消的，如果任务已经在执行过程中了，你可以选择不取消，或者直接打断执行中的任务。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">两个方法具体的执行步骤和原理见上一章节源码解析。</p>
</div><div class="cl-preview-section"><h3 id="thread.yield-方法在工作中有什么用？">1.11 Thread.yield 方法在工作中有什么用？</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：yield 方法表示当前线程放弃 cpu，重新参与到 cpu 的竞争中去，再次竞争时，自己有可能得到 cpu 资源，也有可能得不到，这样做的好处是防止当前线程一直霸占 cpu。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们在工作中可能会写一些 while 自旋的代码，如果我们一直 while 自旋，不采取任何手段，我们会发现 cpu 一直被当前 while 循环占用，如果能预见 while 自旋时间很长，我们会设置一定的判断条件，让当前线程陷入阻塞，如果能预见 while 自旋时间很短，我们通常会使用 Thread.yield 方法，使当前自旋线程让步，不一直霸占 cpu，比如这样：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">boolean</span> stop <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
<span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token operator">!</span>stop<span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token comment">// dosomething</span>
  Thread<span class="token punctuation">.</span><span class="token function">yield</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><h3 id="wait和sleep的相同点和区别">1.12 wait()和sleep()的相同点和区别?</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：相同点：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">两者都让线程进入到 TIMED_WAITING 状态，并且可以设置等待的时间。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">不同点：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">wait 是 Object 类的方法，sleep 是 Thread 类的方法。</li>
<li style="font-size: 20px; line-height: 38px;">sleep 不会释放锁，沉睡的时候，其它线程是无法获得锁的，但 wait 会释放锁。</li>
</ol>
</div><div class="cl-preview-section"><h3 id="写一个简单的死锁-demo">1.13 写一个简单的死锁 demo</h3>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token comment">// 共享变量 1</span>
<span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> Object share1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 共享变量 2</span>
<span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> Object share2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token annotation punctuation">@Test</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testDeadLock</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> InterruptedException <span class="token punctuation">{</span>
  <span class="token comment">// 初始化线程 1，线程 1 需要在锁定 share1 共享资源的情况下再锁定 share2</span>
  Thread thread1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">&gt;</span> <span class="token punctuation">{</span>
    <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>share1<span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token keyword">try</span> <span class="token punctuation">{</span>
        Thread<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">2000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>share2<span class="token punctuation">)</span><span class="token punctuation">{</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"{} is run"</span><span class="token punctuation">,</span>Thread<span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment">// 初始化线程 2，线程 2 需要在锁定 share2 共享资源的情况下再锁定 share1</span>
  Thread thread2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">-</span><span class="token operator">&gt;</span> <span class="token punctuation">{</span>
    <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>share2<span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token keyword">try</span> <span class="token punctuation">{</span>
        Thread<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">2000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
      <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>share1<span class="token punctuation">)</span><span class="token punctuation">{</span>
        log<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span><span class="token string">"{} is run"</span><span class="token punctuation">,</span>Thread<span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// 当线程 1、2 启动后，都在等待对方锁定的资源，但都得不到，造成死锁</span>
  thread1<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  thread2<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  Thread<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">1000000000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><h2 id="总结" style="font-size: 30px;">2 总结</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">线程章节算是中等难度，我们需要清楚线程的概念，线程如何初始化，线程的状态变更等等问题，这些知识点都是线程池、锁的基础，学好线程后，再学习线程池和锁就会轻松很多。</p>
</div>}
                        </div>
                    </div>
                                            <!-- 买过的阅读 -->
                        <div class="art-next-prev clearfix">
                                                                                                <!-- 已买且开放 或者可以试读 -->
                                    <a href="/read/47/article/870">
                                                                    <div class="prev l clearfix">
                                        <div class="icon l">
                                            <i class="imv2-arrow3_l"></i>
                                        </div>
                                        <p>
                                            28 Future、ExecutorService 源码解析   
                                        </p>
                                    </div>
                                </a>
                                                                                                                            <!-- 已买且开放 或者可以试读 -->
                                    <a href="/read/47/article/872">
                                                                    <div class="next r clearfix">
                                        <p>
                                            30 AbstractQueuedSynchronizer 源码解析（上）
                                        </p>
                                        <div class="icon r">
                                            <i class="imv2-arrow3_r"></i>
                                        </div>

                                    </div>
                                </a>
                                                    </div>
                                    </div>
                <div class="comments-con js-comments-con" id="coments_con">
                </div>

                
            </div>
            
            
            

        </div>
    </div>
</div>

<div class="modal modal-jiaQun-new hide" id="modal-jiaQun">
    <div class="inner" style="">
        <div class="modal-close js-close-jiaQun">
            <i class="imv2-close"></i>
        </div>
        <div class="content">
            <img src="https://img4.mukewang.com/5d634d40000119e505400602.jpg">
            <div class="right-info">
                <div class="title">
                    扫码加入慕课Java核心用户群
                </div>
                <div class="desc">
                                            <p class="mb6">验证信息：<span id="joincode">1909271435058473</span><span class="copy js-copy-joincode">复制</span></p>
                                        <p class="mb6">QQ讨论群号：906691736</p>
                                            <p>QQ群URL：<a href="https://jq.qq.com/?_wv=1027&amp;k=55RtSbJ" target="_blank">点击访问</a></p>
                                    </div>
            </div>
            <p class="tip">若遇到搜索不到QQ群或加群失败，请联系客服邮箱:kf@imooc.com</p>
        </div>
    </div>
</div>
 
<!-- 专栏介绍页专栏评价 -->

<!-- 专栏介绍页底部三条评价 -->

<!-- 专栏阅读页弹层目录和介绍页页面目录 -->

<!-- 专栏阅读页发布回复 -->

<!-- 专栏阅读页发布评论 -->

<!-- 专栏阅读页底部评论 -->

<!-- 专栏阅读 单个 评论 -->

<!-- 新增回复和展开三条以外回复 -->

<!-- 立即订阅的弹窗 -->












</div></body></html>